package com.spring.mvc.mina.test;

import java.nio.ByteBuffer;
import java.nio.CharBuffer;

public class BufferFillDrain {

	private static int index=0;
	
	private static String[] strings={
			"A random string, value ",
			"The product of an, infinite number of monkeys ",
			"Hey hey we're the, Monkees ",
			"Opening act for the, Monkees: Jimi Hendrix ",
			"'Scuse me while I, kiss the fly ",//Sorry Jimi ; -)
			"Help Me! Help Me!"
	};
	
	private static boolean drainBuffer(CharBuffer buffer){
		while(buffer.hasRemaining()){
			char c=buffer.get();
			if(c==','){
				buffer.compact();
				break;
			}
			System.out.print(c);
		}
		System.out.println();
		System.out.println(buffer.remaining());
		return buffer.hasRemaining();
	}
	
	private static boolean fillBuffer(CharBuffer buffer){
		if(index>=strings.length){
			return false;
		}
		String s=strings[index++];
		for (int i = 0; i < s.length(); i++) {
			buffer.put(s.charAt(i));
		}
		return true;
	}
	
	public static void main(String[] args) {
		CharBuffer buffer=CharBuffer.allocate(100);
		while(fillBuffer(buffer)){
			buffer.flip();
			System.out.println("******************************************");
			if(!drainBuffer(buffer))
				buffer.clear();
		}
		
		ByteBuffer btBuffer=ByteBuffer.allocate(10);
		for (int i = 0; i < 6; i++) {
			System.out.println(btBuffer.limit()+":"+btBuffer.position());
			btBuffer.put((byte)i);
		}
		btBuffer.flip();
		System.out.println(btBuffer.limit()+":"+btBuffer.position());
		System.out.println(btBuffer.get());
		System.out.println(btBuffer.limit()+":"+btBuffer.position());
		System.out.println(btBuffer.get());
		System.out.println(btBuffer.limit()+":"+btBuffer.position());
		System.out.println(btBuffer.get());
		System.out.println(btBuffer.limit()+":"+btBuffer.position());
		System.out.println(btBuffer.get());
		System.out.println(btBuffer.limit()+":"+btBuffer.position());
		System.out.println(btBuffer.remaining());
		System.out.println(btBuffer.hasRemaining());
	}
}
